<?php


namespace app\cdkjt\controller;


use data\extend\cdkjt\Cdkjt;
use data\model\VslOrderCustom;
use data\model\VslOrderGoodsModel;
use data\model\VslOrderModel;
use data\service\cdkjt\CdkjtService;
use think\Controller;
use think\Request;

class Jssign extends Controller
{

    private $redis;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->redis = CdkjtService::connectRedis();
    }

    //加签页
    public function index()
    {
        return $this->fetch('/cdkjt/jssign/index');
    }

    //获取加签原文
    public function getSignText()
    {
        $sessionID = $this->redis->rPop(CdkjtService::$queue_signs);
        if($sessionID){       //如果存在订单号,构造签名原始数据
            $orderCustom = VslOrderCustom::where(['sessionID'=>$sessionID])->find();
            if($orderCustom){
                $result = $this->_buildResult($orderCustom);
                $signInit = $result['signValue'];                       //加密原始数据
                $result['signValue'] = '';
                $orderCustom->content = base64_encode(json_encode($result));
                $orderCustom->save();
                //更新custom表的content
                $signData = [
                    'signInit'      =>  $signInit,
                    'sessionId'     =>  $sessionID,
                ];
                return json(['code'=>1,'msg'=>'获取数据成功','data'=>$signData]);
            }
        }
        return json(['code'=>0,'msg'=>'没有待加签数据'.date('Y-m-d H:i:s')]);
    }


    //接收加签后的密文
    public function postSignText(){
        $sessionId  = $this->request->post('sessionId');
        $signval    = $this->request->post('signval');
        $orderCustom = VslOrderCustom::where(['sessionID'=>$sessionId])->find();
        if($orderCustom){
            $orderCustom->sign = $signval;
            $orderCustom->updatetime = date('Y-m-d H:i:s');
            $orderCustom->save();
            $this->redis->lPush(CdkjtService::$queue_orders,$sessionId);
        }
        return 1;
    }

    //构造179上传数据
    public function _buildResult($orderCustom,$type=1)
    {
        $orderNo    = $orderCustom['orderNo'];
        $sessionID  = $orderCustom['sessionID'];
        $time       = (string)$orderCustom['serviceTime'];
        $certNo     = \think\Config::get('cdkjt.certNo');
        $OrderInfo  = VslOrderModel::where(['order_no'=>$orderNo])->field('*')->find();

        $cdkjt = new Cdkjt();
        $guid = $cdkjt->create_guid();
        //支付原始数据表头
        $payExchangeInfoHead = [
            "guid"              =>  $guid,
            'initalRequest'     =>  htmlspecialchars_decode($OrderInfo->pay_request),//支付原始请求内容
            //'initalResponse'    =>  htmlspecialchars_decode($OrderInfo->pay_response),//支付原始响应内容
            'initalResponse'    =>  "ok",
            "ebpCode"           =>  \think\Config::get('cdkjt.ebpCode'),//电商平台的海关注册登记编号
            "payCode"           =>  \think\Config::get('cdkjt.payCode'),//支付企业的海关注册登记编号。    //4403169D3W(微信),31222699S7(支付宝)
            "payTransactionId"  =>  $OrderInfo['transaction_id'],             //交易唯一编号（可在央行认可的机构验证）
            "totalAmount"       =>  (float)$OrderInfo['pay_money'],        //实际交易金额
            "currency"          =>  "142",       //实际交易币制（海关编码）
            "verDept"           =>  "3",            //1-银联 2-网联 3-其他
            "payType"           =>  "4",            //用户支付的类型。1-APP 2-PC 3-扫码 4-其他
            "tradingTime"       =>  (string)date('YmdHis',$OrderInfo['pay_time']),
            "note"              =>  '',
        ];
        if($type == 1){
            $payExchangeInfoHead['initalRequest'] = stripslashes($payExchangeInfoHead['initalRequest']);
        }

        $goodsInfo = [];
        $orderGoodsList = VslOrderGoodsModel::where(['order_id'=>$OrderInfo['order_id']])->select();

        foreach ($orderGoodsList as $k=>$item){
            $goodsInfo[$k]["gname"]     = $item->goods_name ." ".$item->sku_name;
            $goodsInfo[$k]["itemLink"]  = \think\Config::get('cdkjt.webdomain')."/wap/goods/detail/".$item->goods_id;
            //$goodsInfo[$k]["itemLink"] = 'no';
        }
        //支付原始数据表体
        $payExchangeInfoLists[] = [
            'orderNo'           =>  $OrderInfo['order_no'],
            'goodsInfo'         =>  $goodsInfo,
            'recpAccount'       =>  \think\Config::get('cdkjt.recpAccount'),            //收款账号
            'recpCode'          =>  \think\Config::get('cdkjt.recpCode'),               //收款企业代码
            'recpName'          =>  \think\Config::get('cdkjt.recpName'),               //收款企业名称
            //'recpName'          =>  'weixin',               //收款企业名称
        ];
        //$payExchangeInfoHead = json_encode($payExchangeInfoHead);

        $i = 0;
        $payExchangeInfoHeadStr = '{';
        foreach ($payExchangeInfoHead as $k=>$v){
            if($i > 0){
                $payExchangeInfoHeadStr .=',';
            }
            if($k == 'totalAmount'){
                $payExchangeInfoHeadStr .='"'.$k.'":'.(float)$v.'';
            }else{
                $payExchangeInfoHeadStr .='"'.$k.'":"'.$v.'"';
            }

            $i++;
        }
        $payExchangeInfoHeadStr .= '}';
        //$payExchangeInfoHeadStr = stripslashes(json_encode($payExchangeInfoHead));
        $initSign = '"sessionID":"'.$sessionID.'"||"payExchangeInfoHead":"'.$payExchangeInfoHeadStr.'"||"payExchangeInfoLists":"'.stripslashes(json_encode($payExchangeInfoLists,JSON_UNESCAPED_UNICODE)).'"||"serviceTime":"'.$time.'"';
        $signValue = $initSign;
        $result = [
            'sessionID'             =>  $sessionID,
            'payExchangeInfoHead'   =>  $payExchangeInfoHead,
            'payExchangeInfoLists'  =>  $payExchangeInfoLists,
            'serviceTime'           =>  $time,
            'certNo'                =>  $certNo,
            'signValue'             =>  $signValue
        ];
        return $result;
    }


}